const fs = require('fs');
const Router = require('koa-router');
let router = new Router();
import admin_routers from '../route/admin';
import home_routers from '../route/home';
export default function () {
    
    const modulesMap = {'/' : 'home', 'admin' : 'admin'};
    let routeObj = {
        '/': home_routers || [],
        'admin': admin_routers || [],
    };
    
    for (let modules in routeObj) {
        let routeModules = routeObj[modules];
        if (Array.isArray(routeModules) && routeObj[modules].length > 0) {
            for (let index in routeModules) {
                let routeArray = routeModules[index];
                let [url, controllerandaction, method] = routeArray;
                // 结构控制器文件
                let [controller, action] = controllerandaction.split('@');
                let controllerFile = `${global['BASE_PATH']}/${modulesMap[modules]}/controller/${controller}.js`;
                if (!fs.existsSync(controllerFile)) {
                    continue;
                }
                let uri = `/${modules}${url}`.replace(/\/+/g, '/');
                if (!method) method = 'all';
                router[method](uri, async (ctx, next) => {
                    ctx.isAjax = ctx.request.header['x-requested-with'] === 'XMLHttpRequest';
                    let ctrl = require(controllerFile);
                    ctx.body = ctx.request.body;
                    let ctrlClass = new ctrl(ctx);
                    await ctrlClass[action]();
                });

            }
        }
    }
    return router.routes();
};
